import { combineResolvers } from 'graphql-resolvers'
import { pageModel } from '../../lib/helper'
import auth from '../../middlewares/auth'

let createComment = combineResolvers(
  auth,
  async (root, { input }, { models: {Answer, Progress}, services: { $comment }, user }) => {
    input.userId = user.id
    let rs = await $comment.createOrUpdate(input)
    let {isNeedRedo, answerId} = input
    if (isNeedRedo && answerId) {
      let answer = await Answer.findById(answerId)
      let progress = await Progress.findById(answer.progressId)
      progress.state = 'redo'
      await progress.save()
    }
    return rs
  }
)

let removeComment = combineResolvers(
  auth,
  async (root, { id }, { services: { $comment }, user }) => {
    let userId = user.id
    console.info('remove comment:', id)
    return await $comment.remove(id, userId)
  }
)

let createRating = combineResolvers(
  auth,
  async (root, { input }, { services: { $comment }, user }) => {
    input.userId = user.id
    return await $comment.createOrUpdate(input)
  }
)

let removeRating = combineResolvers(
  auth,
  async (root, { input }, { services: { $comment }, user }) => {
    input.userId = user.id
    return await $comment.removeRating(input)
  }
)

const createBulkCommentsForTask = combineResolvers(
  auth,
  async (root, { taskId, userIds, data, isNeedRedo = true }, { services: { $comment }, user }) => {
    let task = await $comment.createBulkForTask({userId: user.id, taskId, userIds, data, isNeedRedo})
    return task
  }
)

module.exports = {
  Mutation: {
    createCommentForAnswer: createComment,
    createRatingForProgress: createRating,
    removeRatingForProgress: removeRating,
    createBulkCommentsForTask,
  }
}
